using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MvcDemo.Db;
using MvcDemo.Models;

namespace MvcDemo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly MvcDb _db;
        private readonly DbSet<T> _table;
        public IQueryable<T> Table{
            get{
                return _table as IQueryable<T>;
            }
        }
        public EfRepository()
        {
            _db =new MvcDb();
            _table =_db.Set<T>();
        }

        public void Delete(int id)
        {
            var entity = _table.Where(x=>x.IsDeleted==false && x.Id==id).FirstOrDefault();
            entity.UpdatedTime=DateTime.Now;
            entity.IsDeleted=true;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public T GetById(int id)
        {
             var entity = _table.Where(x=>x.IsDeleted==false && x.Id==id).FirstOrDefault();
             return entity;
        }

        public void Insert(T entity)
        {
            entity.IsActived=true;
            entity.IsDeleted=false;
            entity.CreatedTime=DateTime.Now;
            entity.UpdatedTime=DateTime.Now;
            entity.Creator=0;
            entity.DisplayOrder=0;
            _table.Add(entity);
            _db.SaveChanges();
            
        }

        public void Update(T entity)
        {
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}